<?php
class WidgetApps_WpTravel {
	
	static $LIBROOT;
	static $RESULTS_PROCESSED;
	
	function WidgetApps_WpTravel($libroot)
	{
		WidgetApps_WpTravel::$LIBROOT = $libroot;
		WidgetApps_WpTravel::$RESULTS_PROCESSED = false;
	}
	
	function init()
	{
		global $wp_rewrite;
   		$wp_rewrite->flush_rules();
   
		wp_enqueue_script('ui.datepicker', WP_PLUGIN_URL . '/widgetapps-wptravel/js/ui.datepicker.js');
		wp_enqueue_script('wptravel.admin', WP_PLUGIN_URL . '/widgetapps-wptravel/js/wptravel-admin.js');
	}
	
	function processSearch($query)
	{
		if(!empty($query->query_vars['watw_action'])){
			include(WidgetApps_WpTravel::$LIBROOT . '/templates/searchresults.php');
			exit(0);
		}
	}
	
	function addHeaderCode()
	{
		echo '<link type="text/css" rel="stylesheet" href="' . WP_PLUGIN_URL . '/widgetapps-wptravel/css/wptravel-widget.css" />' . "\n";
	}
	
	function processContent( $content = '' )
	{
		$this->addScheduledDates( $content );
		
		return $this->addScheduledDates( $content );
	}
	
	function addQueryVars($qvars)
	{
		array_push($qvars, 'watw_action', 'watw_type');
		return $qvars;
	}
	
	function addRewriteRule($rules)
	{
		$newrules = array();
		$newrules['watw/(.+)$'] = 'index.php?watw_action=search&watw_type=$matches[1]';
		return $newrules + $rules;
	}
	
	function add2Excerpt( $content = '' )
	{
		//$this->addCustomFieldData();
		return $content;
	}
	
	function widgetInit()
	{
		register_widget('WidgetApps_Widget_Date');
		register_widget('WidgetApps_Widget_Price');
	}
	
	function pluginAdminMenu()
	{
		add_options_page('Travel Plugin Options', 'Travel Plugin', 8, (WidgetApps_WpTravel::$LIBROOT . '/templates/adminOptions.php') );
	}
	
	// Register the options the plugin needs.
	function registerSettings()
	{
		register_setting( 'wa-travel-options', 'wa_option1' );
		register_setting( 'wa-travel-options', 'wa_option2' );
		register_setting( 'wa-travel-options', 'wa_option3' );
	}
	
	// Add the meta box to the write/edit post
	function addCustomBox()
	{
		add_meta_box( 'wptravel_metabox', __( 'Scheduled Dates', 'wptravel_textdomain' ), 
                array($this, 'renderScheduledDates'), 'post', 'side', 'high' );
	}
	
	function adminCss()
	{
		echo '<link type="text/css" rel="stylesheet" href="' . WP_PLUGIN_URL . '/widgetapps-wptravel/css/ui.datepicker.css" />' . "\n";
	}
	
	function renderScheduledDates()
	{
		include(WidgetApps_WpTravel::$LIBROOT . '/templates/metabox_scheduleddates.php');
	}
	
	// Save the data entered into the meta box
	function savePostData( $post_id )
	{
		global $wpdb;
	  // verify this came from the our screen and with proper authorization,
	  // because save_post can be triggered at other times
	  
	  if ( !wp_verify_nonce( $_POST['wptravel_noncename'], plugin_basename(__FILE__) )) {
	    //return $post_id;
	  }
	
	  // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
	  // to do anything
	  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
	    return $post_id;
	
	  
	  // Check permissions
	    if ( !current_user_can( 'edit_post', $post_id ) )
	      return $post_id;
	
	  // OK, we're authenticated: we need to find and save the data
	  
	  $scheduledDates = $_POST['wptravel_scheduledDate'];
	  
  	// delete all the schedule data, we'll add it in again below.
  	$wpdb->query( $wpdb->prepare( "DELETE FROM wp_wptravel WHERE post_ID = %d", $post_id ) );
	  
	  foreach($scheduledDates as $scheduledDate){
	  	$data = explode(':', $scheduledDate);
	  	
  	
	  	if (!in_array($data[7], array('single', 'double', 'triple', 'quad', 'group'))){
	  		$data[7] = 'single';
	  	}
	  	
	  	if (!in_array($data[3], array('CDN', 'USD', 'EUR'))){
	  		$data[3] = 'CDN';
	  	}
	  	
	  	if ($data[4] == 'true'){
	  		$data[4] = 'y';
	  	} else {
	  		$data[4] = 'n';
	  	}
	  	
	  	if ($data[5] == 'true'){
	  		$data[5] = 'y';
	  	} else {
	  		$data[5] = 'n';
	  	}
	  	
	  	if ($data[6] == 'true'){
	  		$data[6] = 'y';
	  	} else {
	  		$data[6] = 'n';
	  	}
	  	
	  	if ($data[8] == 'true'){
	  		$data[8] = 'y';
	  	} else {
	  		$data[8] = 'n';
	  	}
	  	
	  	
	  	$wpdb->query( $wpdb->prepare( "INSERT INTO wp_wptravel
				( post_ID, startDate, endDate, price, currency, closed, guaranteed, limited, accommodation, airIncluded )
				VALUES ( %d, %s, %s, %f, %s, %s, %s, %s, %s, %s )", 
        		$post_id, $data[0], $data[1], $data[2], $data[3], $data[4], $data[5], $data[6], $data[7], $data[8] ) );
	  	
	  }
	  
	   return $scheduledDates;
	}
	
	function deletePostData( $post_id )
	{
		global $wpdb;
		
	    if ( !current_user_can( 'delete_post', $post_id ) )
	      return $post_id;
		
        $wpdb->query( $wpdb->prepare( "DELETE FROM wp_wptravel WHERE post_ID = %d", $post_id ) );
	}
	
	private function processTravelSearch()
	{
		include(WidgetApps_WpTravel::$LIBROOT . '/templates/searchresults.php');
	}
	
	private function addScheduledDates( $content )
	{
		global $post;
		global $wpdb;
		
		$sql = "SELECT * FROM " . $wpdb->prefix . "wptravel WHERE closed = 'n' AND post_ID = " . $post->ID;
		
		$foundDates = $wpdb->get_results($sql, OBJECT);
		
		$html = '';
		
		if (count($foundDates) > 0){
			$html  = '<div id="wptravel_scheduledDatesPanel">';
			$html .= '<table>';
			$html .= '<thead>';
			$html .= '<tr>';
			$html .= '<td colspan="4">Scheduled Dates</td>';
			$html .= '</tr>';
			$html .= '<tr>';
			$html .= '<td>Start Date</td>';
			$html .= '<td>End Date</td>';
			$html .= '<td>Price</td>';
			$html .= '<td>Accommodation</td>';
			$html .= '</tr>';
			$html .= '</thead>';
			$html .= '<tbody>';
			
			$rowcount = 0;
			foreach ($foundDates as $foundDate){
				$rowcount++;
				
				$rowstyle = ($rowcount % 2) + 1;
				$rowstyle = 'wptravel_daterow' . $rowstyle;
				
				$deets = array();
				if ($foundDate->limited == 'y'){
					$deets[] = 'Limited Availability';
				}
				
				if ($foundDate->air == 'y') {
					$deets[] = 'Air Included';
				} else {
					$deets[] = 'Air NOT Included';
				}
				
				if ($foundDate->guaranteed != 'y'){
					$deets[] = 'Not Guaranteed';
				}
				
				$html .= '<tr class="' . $rowstyle . '">';
				$html .= '<td>' . date('F j, Y', strtotime($foundDate->startDate)) . '</td>';
				$html .= '<td>' . date('F j, Y', strtotime($foundDate->endDate)) . '</td>';
				$html .= '<td>$' . $foundDate->price . ' ' . $foundDate->currency . '</td>';
				$html .= '<td>' . $foundDate->accommodation . '</td>';
				$html .= '</tr>';
				$html .= '<tr class="' . $rowstyle . '">';
				$html .= '<td colspan="4">* ' . implode(', ', $deets) . '</td>';
				$html .= '</tr>';
			}
			
			$html .= '</tbody>';
			$html .= '</table>';
			$html .= '</div>';
		} else {
			//$html = '<p>There are currently no scheduled dates.</p>';
		}
		
		if (strpos($content, '[wptravel_dates]') === false){
			return $html . $content;
		}
		
		return str_replace('[wptravel_dates]', $html, $content);
	}
}